package com.quan.system.web.controller;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.quan.amqp.producer.OSSMessageProducer;
import com.quan.common.base.annotation.Log;
import com.quan.common.base.bean.PageBean;
import com.quan.common.base.bean.ResponseMsg;
import com.quan.common.base.bean.ResultBean;
import com.quan.common.core.BaseController;
import com.quan.common.sdk.oss.qiniu.QiniuOSSUtils;
import com.quan.system.entity.SystemOss;
import com.quan.system.service.SystemOssService;

import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * <p>
 * 系统管理-OSS文件上传 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2018-07-05
 */
@RestController
@RequestMapping("/system/oss")
public class SystemOssController extends BaseController {

    @Autowired 
    private SystemOssService systemOssService;
    
    @Autowired
    private QiniuOSSUtils qiniuOSSUtils;
    
    @Autowired
	private OSSMessageProducer ossMessageProducer;

	/**
     * 添加
     * @param  entity 实体
     * @return ResultBean
     */
    @PostMapping("/add")
    public Object add(@Valid @RequestBody SystemOss entity, BindingResult bindingResult) {
    	if (bindingResult.hasErrors()) {
			return ResultBean.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}
		SystemOss insertSelective = this.systemOssService.insertSelective(entity);
		if (null != insertSelective) {
			return ResultBean.ok();
		} else {
			return ResultBean.failure();
		}
    }

    /**
     * 删除
     * @param id ID
     * @return ResultBean
     */
    @DeleteMapping("/delete/{id}")
    public Object delete(@PathVariable Integer id) {
    	int count = this.systemOssService.deleteById(id);
    	if(count > 0) {
    		return ResultBean.ok();
    	} else {
    		return ResultBean.failure("通过ID删除失败：[ " + id + " ]");
    	}
    }
    
    /**
     * 批量删除
     * @param params idList(JSON):["1","2"]
     * @return ResultBean
     */
    @Log(desc="批量删除文件")
    @PostMapping("/delete")
    public Object delete(@RequestBody Map<String, Object> params) {
    	if(null != params && !params.isEmpty()) {
    		List<Integer> idList = JSON.parseArray(params.get("idList").toString(), Integer.class);
    		
    		Condition condition = new Condition(SystemOss.class) ;
    		Criteria createCriteria = condition.createCriteria();
    		createCriteria.andIn("id", idList) ;
    		List<SystemOss> listOss = this.systemOssService.selectAllByCondition(condition);
    		
    		int count = this.systemOssService.deleteByIds(StringUtils.join(idList, ","));
        	if(count > 0) {
        		//发送消息删除云端文件
        		this.ossMessageProducer.senderDeleteOssFile(listOss);
        		listOss = null ;
        		return ResultBean.ok("删除成功：["+ count +"]");
        	} else {
        		return ResultBean.failure("通过ID删除失败：[ " + idList + " ]");
        	}
    	}
    	return ResultBean.failure("请选项需要删除的记录");
    }

    /**
     * 修改
     * @param  entity 实体
     * @return ResultBean
     */
    @PostMapping("/update")
    public Object update(@Valid @RequestBody SystemOss entity, BindingResult bindingResult) {
    	if (bindingResult.hasErrors()) {
            return ResultBean.warning(bindingResult.getFieldError().getDefaultMessage().toString()) ;
        }
    	int count = this.systemOssService.updateSelective(entity);
    	if(count > 0) {
    		return ResultBean.ok();
    	} else {
    		return ResultBean.failure();
    	}
    }

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return SystemOss
    */
    @GetMapping("/get/{id}")
    public Object get(@PathVariable Integer id) {
    	SystemOss entity = this.systemOssService.selectOneById(id);
    	if(null != entity) {
    		return ResultBean.ok(entity);
    	} else {
    		return ResultBean.failure("通过ID查询失败：[ " + id + " ]");
    	}
    }
    
    /**
    * 多条件查询数据列表
    *
    * @param entiy 实体对象（查询条件）
    * @return 分页对象
    */
    @GetMapping(value = "/list")
    public Object list(SystemOss entity) {
		return ResultBean.ok(this.systemOssService.selectAll(entity));
    }

    /**
    * 多条件查询分页数据
    *
    * @param entiy 实体对象（查询条件）
    * @return 分页对象
    */
    @GetMapping(value = "/page")
    public Object page(SystemOss entity) {
		return ResultBean.ok(this.systemOssService.selectPage(entity, new PageBean(request)));
    }
    
    /**
     * 上传文件
     * @param request
     * @param ossName 服务商名
     * @param bucketName 空间名
     * @param prefixName 文件前缀
     * @return
     */
    @Log(desc="文件上传")
 	@PostMapping(value = "/upload")
 	public Object uploadAvatar(HttpServletRequest request, String ossName, String bucketName, String prefixName) {
 		try {
 			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

 			// 取得MultiValueMap集合
 			MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
 			Set<Entry<String, List<MultipartFile>>> entrySet = multiFileMap.entrySet();
 			for (Entry<String, List<MultipartFile>> entry : entrySet) {

 				// 获取MultipartFile集合
 				List<MultipartFile> multipartFiles = entry.getValue();
 				for (MultipartFile multipartFile : multipartFiles) {
 					ResponseMsg response = this.qiniuOSSUtils.upload(bucketName, multipartFile.getBytes(), multipartFile.getOriginalFilename(), prefixName) ;
 					if(response.isStatus()) { // 上传成功
 						//文件信息到数据库
 						SystemOss entity = new SystemOss() ;
 						entity.setOssName(ossName);
 						entity.setBucketName(bucketName);
 						entity.setFileName(response.getFname());
 						entity.setFileType(response.getFtype());
 						entity.setUrl(response.getUrl());
 						
 						this.systemOssService.insert(entity) ;
 						
 					} else {
 						return ResultBean.failure("上传失败", response) ;
 					}
 					return ResultBean.ok(response);
 				}
 			}
 		} catch (Exception e) {
 			return ResultBean.errorMsg("文件上传失败") ;
 		}
 		return ResultBean.ok();
 	}

}
